package org.apache.ibatis.plugin;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.defaults.Fields;

public class MybatisFactory {

	public static Configuration doResolveConfiguration(Invocation invocation) {
		return doResolve(invocation, Configuration.class);
	}

	public static MappedStatement doResolveMappedStatement(Invocation invocation) {
		return doResolve(invocation, MappedStatement.class);
	}

	@SuppressWarnings("unchecked")
	public static <T> T doResolve(Invocation invocation, Class<T> type) {
		// 通过 invocation 获取代理的目标对象  
		Object target = invocation.getTarget();
		Object[] args = invocation.getArgs();
		if (args != null) {
			for (Object arg : args) {
				if (type.isAssignableFrom(arg.getClass())) {// 参数中包含 type 结束循环
					return (T) arg;
				}
			}
		}

		try {
			return Fields.get(target, type);
		} catch (Exception e) {
			return null;
		}
	}
}
